package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @author: itheima
 * @create: 2022-07-06 14:57
 */
@Slf4j
@Component
public class UpDownListener {

    @Autowired
    private IApArticleService apArticleService;


    /**
     * 文章上下架监听器
     * @param record
     */
    @KafkaListener(topics = "${topic.upDownTopic}")
    public void handlerMsg(ConsumerRecord<String, String> record) {
        if (StringUtils.isNotBlank(record.value())) {
            log.info("【文章微服务】监听文章上下架状态，参数：{}", record.value());
            //将消息JSON字符串转为Map对象
            HashMap map = JSON.parseObject(record.value(), HashMap.class);
            Long articleId = (Long) map.get("articleId");
            Boolean isDown = (Boolean) map.get("isDown");

            LambdaUpdateWrapper<ApArticle> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ApArticle::getId, articleId);
            updateWrapper.set(ApArticle::getIsDown, isDown);
            apArticleService.update(updateWrapper);
        }

    }
}
